package com;

import com.sun.security.ntlm.Server;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Date;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.logging.Level;
import java.util.logging.Logger;

public class Redirector {

    private final static int THREAD_NUM = 100;

    private final static int PORT = 1118;

    private final Logger logger = Logger.getLogger("Redirector");

    private final String newSite;

    private final int port;


    public Redirector(String newSite, int port) {
        this.newSite = newSite;
        this.port = port;
    }

    public void start(){

        ExecutorService tp = Executors.newFixedThreadPool(THREAD_NUM);

        try (ServerSocket server = new ServerSocket(PORT)){

            logger.info("Redirecting connections on port " + server.getLocalPort() + " to " + newSite);

            while (true){

                Socket conn = server.accept();

                logger.info(conn + " has connected with this server.");

                tp.submit(new RedirectorThread(conn));

            }

        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public class RedirectorThread implements Callable<Void>{

        private Socket conn;

        public RedirectorThread(Socket conn) {
            this.conn = conn;
        }

        @Override
        public Void call(){

            try {
                InputStream in = conn.getInputStream();

                Reader reader = new InputStreamReader(new BufferedInputStream(in));

                OutputStream out = conn.getOutputStream();

                Writer writer = new BufferedWriter(new OutputStreamWriter(out,"US-ASCII"));

                StringBuilder request = new StringBuilder(80);

                while (true){

                    int c = reader.read();

                    if(c == '\r' || c == '\n' || c == -1) break;

                    request.append((char)c);

                }

                String get = request.toString();

                System.out.println(get);

                String[] pieces = get.split("\\w*");

                String theFile = pieces[1];

                if(get.indexOf("HTTP") != -1){
                    writer.write("HTTP/1.0 302 FOUND\r\n");
                    Date now = new Date();
                    writer.write("Date: " + now + "\r\n");
                    writer.write("Server: Redirector 1.1\r\n");
                    writer.write("Location: " + newSite + theFile + "\r\n");
                    writer.write("Content-type: text/html\r\n\r\n");
                    writer.flush();
                }

                writer.write("<html><head><title>Document moved</title></head>\r\n");
                writer.write("<body><h1>Document moved</h1>\r\n");
                writer.write("The document " + theFile + " has moved to\r\n <a href=\"" + newSite + theFile + "\""
                            + newSite + theFile + "</a>.\r\n Please update your bookmarks");
                writer.write("</body></html>\r\n");
                writer.flush();
                logger.log(Level.INFO,"Redirected " + conn.getRemoteSocketAddress());

            } catch (IOException e) {

            }finally {

                try {
                    conn.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }


            return null;
        }
    }

    public static void main(String[] args) {

        int thePort;
        String theSite;

        try {

            theSite = args[0];

            if(theSite.endsWith("/")){

                theSite = theSite.substring(0, theSite.length()-1);

            }

        }catch (RuntimeException e){
            return;
        }

        try {
            thePort = Integer.parseInt(args[1]);

        }catch (RuntimeException e){
            thePort = 80;
        }

        Redirector redirector = new Redirector(theSite,thePort);

        redirector.start();

    }

}
